package com.itheima.reggie.common;


import com.itheima.reggie.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //捕获到异常，不管怎么找，都要先打印异常信息
        log.error("GlobalExceptionHandler::exceptionHandler",ex);

        //捕获到异常，不管怎么找，都要先打印异常信息
        log.error(ex.toString());

        log.info("-->{}",ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            //说明该用户已存在
            String[] s = ex.getMessage().split(" ");
            return R.error(s[2]+"已存在");
        }

        return R.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)

    public R<String> customException(CustomException ex){
        //捕获到异常，不管怎么找，都要先打印异常信息
        log.error("GlobalExceptionHandler::customException",ex);
        String msg = ex.getMessage();
        return R.error(msg);
    }

}
